<template>
  <el-dialog
    :close-on-click-modal="false"
    :visible.sync="dialogVisible"
    :title="`修改答案-${form?.type?.name}`"
    class="answer-dialog"
    width="800px"
  >
    <el-form
      ref="formRef"
      v-loading="loading"
      label-position="left"
      :model="form"
      class="form-warp"
      label-width="100px"
    >
      <el-form-item
        v-for="(item, index) in form.answer"
        :key="index"
        :label="`答案内容${index + 1}`"
        :prop="'answer.' + index + '.content'"
        :rules="{
          required: true, message: '答案内容不能为空', trigger: ['blur', 'change']
        }"
      >
        <div class="answer-box">
          <div style="flex: 1;">
            <el-input
              v-if="item.id"
              v-model="item.content"
              autosize
              placeholder="请输入答案内容"
              type="textarea"
              :readonly="item.id !== answerId"
            />
            <el-input
              v-if="!item.id"
              v-model="item.content"
              autosize
              placeholder="请输入答案内容"
              type="textarea"
            />
          </div>
          <div class="btn-box">
            <template v-if="item.id && item.id !== answerId">
              <el-tooltip :enterable="false" class="item" effect="dark" content="编辑" placement="top-start">
                <el-button type="primary" icon="el-icon-edit" circle @click="editAnswer(item)" />
              </el-tooltip>
              <el-tooltip :enterable="false" class="item" effect="dark" content="删除" placement="top-start">
                <el-button type="danger" icon="el-icon-delete" circle @click="deleteAnswer(item)" />
              </el-tooltip>
              <el-tooltip :enterable="false" class="item" effect="dark" content="设为答案" placement="top-start">
                <el-button type="warning" :icon="item.is_ok === 1 ? 'el-icon-star-on' : 'el-icon-star-off'" circle @click="setAnswer(item)" />
              </el-tooltip>
              <!-- <div style="display: flex; align-items: center;">
                <span style="margin: 0 10px;">答案</span>
                <el-switch
                  v-model="item.is_ok"
                />
              </div> -->
            </template>
            <template v-if="!item.id || item.id === answerId">
              <el-button type="primary" icon="el-icon-check" circle @click="submitChange(item)" />
              <el-button type="danger" icon="el-icon-close" circle @click="handleCancel(item)" />
            </template>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div v-if="showAddNewAnswerButton" class="btn-box">
      <!-- <el-button type="primary">确定</el-button> -->
      <el-button type="primary" @click="addNewAnswer">添加选项</el-button>
    </div>
  </el-dialog>
</template>

<script>
import lodash from 'lodash'
import {
  deleteAnswer,
  editOrCreateAnswer,
  getTestQuestionDetails
} from '@/api/examination'
export default {
  name: 'EditAnswerDialog',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    testQuestionId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      form: {
        answer: []
      },
      answerId: null,
      currentAnswer: null
    }
  },
  computed: {
    showAddNewAnswerButton() {
      let flag = 0
      this.form.answer.forEach(item => {
        if (!item.id) flag++
      })
      return !flag > 0
    }
  },
  watch: {
    show(n, o) {
      this.dialogVisible = n
      if (n) {
        this.getTestQuestionDetails()
      } else {
        this.reset()
        setTimeout(() => {
          this.form.answer = []
        }, 0)
      }
    },
    dialogVisible: {
      immediate: true,
      handler: function(n, o) {
        this.$emit('update:show', n)
      }
    }
  },
  created() {

  },
  methods: {

    async getTestQuestionDetails() {
      this.loading = true
      try {
        const res = await getTestQuestionDetails(this.testQuestionId)
        console.log('res getTestQuestionDetails ------>', res)
        this.form.answer = res.data.content
        this.form.type = res.data.type
      } catch (error) {
        this.$message.error('答案选项获取失败')
      } finally {
        this.loading = false
      }
    },

    deleteAnswer(item) {
      this.$confirm('是否删除该项答案', '提示', { type: 'warning' })
        .then(() => {
          const index = this.form.answer.indexOf(item)
          if (index !== -1) {
            this.form.answer.splice(index, 1)
            this.deleteAnswerApi(item.id)
          }
        })
    },

    async deleteAnswerApi(id) {
      try {
        const res = await deleteAnswer({ id })
        if (res.status === 'success') this.$message.success('删除成功')
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    editAnswer(item) {
      console.log('item ------>', item)
      this.answerId = item.id
      this.currentAnswer = lodash.cloneDeep(item)
    },

    addNewAnswer() {
      this.form.answer.push({ content: '' })
    },

    handleCancel(item) {
      const index = this.form.answer.indexOf(item)
      if (item.id) {
        this.answerId = null
        this.form.answer[index] = this.currentAnswer
      } else {
        if (index !== -1) {
          this.form.answer.splice(index, 1)
        }
      }
    },

    submitChange(item) {
      this.$refs.formRef?.validate(valid => {
        if (!valid) return
        let params = {}
        params = item.id
          ? {
            id: item.id,
            content: item.content,
            is_ok: item.is_ok
          }
          : {
            topic_id: this.testQuestionId,
            content: item.content,
            is_ok: 0
          }
        this.editOrCreateAnswerApi(params)
      })
    },

    async editOrCreateAnswerApi(params, refresh = true) {
      try {
        const res = await editOrCreateAnswer(params)
        console.log('res editOrCreateAnswerApi ------>', res)
        if (res.status === 'success') {
          this.$message.success('修改成功')
          this.reset(refresh)
        }
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    reset(refresh = false) {
      this.answerId = null
      if (refresh) {
        this.getTestQuestionDetails()
      }
    },

    setAnswer(item) {
      item.is_ok = item.is_ok === 1 ? 0 : 1
      const params = item.id
        ? {
          id: item.id,
          content: item.content,
          is_ok: item.is_ok
        }
        : {
          topic_id: this.testQuestionId,
          content: item.content
        }

      this.editOrCreateAnswerApi(params, true)
    }
  }

}

</script>
<style scoped lang='scss'>
.answer-dialog {
  .form-warp {
    min-height: 200px;
  }
  .answer-box {
    display: flex;
    align-items: center;
  }
  .btn-box{
    margin: 0 0 0 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
